<?php

namespace App\Services\WechatApi;

use YQ\YqCurl;

class WechatApiOffiAccount extends WechatApiBase
{
    /**
     * 创建自定义菜单
     * https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Creating_Custom-Defined_Menu.html
     */
    public function menuCreate($access_token, $params)
    {
        $api = "cgi-bin/menu/create?access_token={$access_token}";
        $url = "{$this->host}{$api}";
        $res = YqCurl::curl($url, json_encode($params, JSON_UNESCAPED_UNICODE), 1, 1);
        yqlog($res);
        if (!$res) {
            return false;
        }

        $res = json_decode($res, true);
        if (isset($res['errcode']) && $res['errcode'] != 0) {
            return false;
        }

        return true;
    }

    /**
     * 删除自定义菜单
     * https://developers.weixin.qq.com/doc/offiaccount/Custom_Menus/Deleting_Custom-Defined_Menu.html
     */
    public function menuDelete($access_token)
    {
        $api = "cgi-bin/menu/delete?access_token={$access_token}";
        return $this->send($api, [], 'get');
    }

    /**
     * 获取素材列表
     * https://developers.weixin.qq.com/doc/offiaccount/Asset_Management/Get_materials_list.html
     */
    public function batchGetMaterial($access_token, $params)
    {
        $api = "cgi-bin/material/batchget_material?access_token={$access_token}";
        $url = "{$this->host}{$api}";
        $res = YqCurl::curl($url, json_encode($params, JSON_UNESCAPED_UNICODE), 1, 1);
        if (!$res) {
            return false;
        }

        $res = json_decode($res, true);
        if (isset($res['errcode']) && $res['errcode'] != 0) {
            return false;
        }

        return $res;
    }



    /**
     * 生成公众号带参数二维码
     * https://developers.weixin.qq.com/doc/offiaccount/Account_Management/Generating_a_Parametric_QR_Code.html
     *
     * @param string $access_token 公众号access_token
     * @param string $scene_str 参数值
     * @param string $action_name 默认为永久字符串参数的二维码
     * @return string
     */
    public function createQrcode($access_token, $scene_str = '', $action_name = 'QR_LIMIT_STR_SCENE'): string
    {
        $api = "cgi-bin/qrcode/create?access_token={$access_token}";
        $url = "{$this->host}{$api}";
        $params = [
            'action_name' => $action_name,
            'action_info' => [
                'scene' => [
                    'scene_str' => $scene_str
                ]
            ],
        ];
        $res = YqCurl::curl($url, json_encode($params, JSON_UNESCAPED_UNICODE), 1, 1);
        if (!$res) {
            return '';
        }

        $res = json_decode($res, true);
        if (isset($res['errcode']) && $res['errcode'] != 0) {
            return '';
        }

        $ticket = $res['ticket'];
        $qrcode_url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticket);

        return $qrcode_url;
    }
}
